package com.easyedu.signcenter.service;


import com.easyedu.core.exception.EasyEduException;
import com.easyedu.core.redis.RedisUtils;
import com.easyedu.core.util.JwtUtils;
import com.easyedu.signcenter.dao.UserDao;
import com.easyedu.signcenter.entity.DO.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author lmr
 **/
@Service
public class UserService {
    private final Logger LOGGER = LoggerFactory.getLogger(this.getClass());

    private final JwtUtils jwtUtils = new JwtUtils();

    @Resource
    private RedisUtils redisUtils;

    private final UserDao userDao;


    public UserService(UserDao userDao) {
        this.userDao = userDao;
    }


    public Map<String, Object> login(Long userNumber, String password) {
        User user = userDao.getUserByUserNumber(userNumber);
        if (user == null || user.getUserNumber() == 0) {
            LOGGER.error("该用户未被注册：" + userNumber);
            throw new EasyEduException(1999,"用户不存在请注册");
        }
        if (!user.getPassword().equals(password)) {
            LOGGER.error("该用户输入密码错误：" + userNumber);
            throw new EasyEduException(1999,"密码错误请重新输入");
        }
        if (user.getStatus() == 2) {
            LOGGER.error("该用户状态为不可用，请联系管理员！");
            throw new EasyEduException(1999,"用户状态为不可用");
        }
        String token = jwtUtils.createToken(user.getUserid(), user.getUserNumber(), user.getLevel());
        String userTokenKey = "userLoginToken" + userNumber;
        try {
            redisUtils.set(userTokenKey, token);
            redisUtils.expire(userTokenKey, 1, TimeUnit.DAYS);
        } catch (Exception e) {
            LOGGER.error("redis连接失败");
            throw new EasyEduException(1999,"redis连接失败" + e);
        }
        flashLoginTime(userNumber);
        Map<String,Object> res = new HashMap<>();
        res.put("token",token);
        res.put("userName",user.getUserName());
        res.put("level",user.getLevel());
        return res;
    }


    public void logout(Long userNumber) {
        try {
            redisUtils.delete("userLoginToken" + userNumber);
        } catch (Exception exception) {
            LOGGER.error("redis连接失败");
            throw new EasyEduException(1999,"redis连接失败");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public User logon(Long userNumber, String userName, String password) {
        LOGGER.info("执行注册流程");
        List<User> userByUserName = userDao.getUserByUserNameOrUserUserNumber(userName, userNumber);
        if (userByUserName.size() != 0) {
            LOGGER.error("申请注册的用户用户名已被注册！");
            throw new EasyEduException(1999,"该用户名已被注册！");
        }
        User user = new User(userNumber, userName, password);
        int nub = userDao.createNewStudentUser(user);
        if (nub == 0) {
            LOGGER.error("新建用户失败");
            throw new EasyEduException(1999,"创建用户过程发生意外！");
        }
        return user;
    }

    public boolean checkHasUserName(String userName) {
        return userDao.getUserByUserName(userName) != null;
    }

    public boolean checkHasUserNumber(Long userNumber) {
        return userDao.getUserByUserNumber(userNumber) != null;
    }

    @Async
    public void flashLoginTime(Long userNumber) {
        userDao.flashLoginTime(userNumber);
    }
}
